package frontend

import (
	"LeastMall/models"
	"fmt"
	"net/url"
	"strings"

	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) BaseInit() {
	topMenu := []models.Menu{}

	if hasTopMenu := models.CacheDb.Get("topMenu", &topMenu); hasTopMenu {
		c.Data["topMenuList"] = topMenu
	} else {
		//找到topMenu对应的表，满足where条件后，按照sort字段降序排列
		models.DB.Where("status=1 AND position=1").Order("sort desc").Find(&topMenu)
		c.Data["topMenuList"] = topMenu
		models.CacheDb.Set("topMenu", topMenu)
	}

	productCate := []models.ProductCate{}

	if hasProductCate := models.CacheDb.Get("productCate", &productCate); hasProductCate {
		c.Data["productCateList"] = productCate
	} else {
		//首先从productCate表里查找满足where条件的条目，按照sort降序排列，然后对每条数据的productcateitem里面的数据
		//按照preload内的where条件进行筛选，在按preload里的order排序
		models.DB.Preload("ProductCateItem", func(db *gorm.DB) *gorm.DB {
			return db.Where("product_cate.status=1").
				Order("product_cate.sort DESC")
		}).Where("pid=0 AND status=1").Order("sort desc", true).
			Find(&productCate)
		c.Data["productCateList"] = productCate
		models.CacheDb.Set("productCate", productCate)
	}

	middleMenu := []models.Menu{}

	if hasMiddleMenu := models.CacheDb.Get("middleMunu", &middleMenu); hasMiddleMenu {
		c.Data["middleMenuList"] = middleMenu
	} else {
		// models.DB.Where("status=1 AND position=2").Order("sort desc").Find(&middleMenu)
		//筛选出每条menu后，获得其中relation关联productids然后通过该id检索product表满足where条件，获取前面
		//六条数据在按照sort降序排列，在存入menu的productItem字段中
		for i := 0; i < len(middleMenu); i++ {
			middleMenu[i].Relation = strings.ReplaceAll(middleMenu[i].Relation, "，", ",")
			relation := strings.Split(middleMenu[i].Relation, ",")
			product := []models.Product{}
			models.DB.Where("id in (?)", relation).Limit(6).Order("sort desc").
				Select("id,title,product_img,price").Find(&product)
			middleMenu[i].ProductItem = product
		}
		c.Data["middleMenuList"] = middleMenu
		models.CacheDb.Set("middleMenu", middleMenu)
	}

	user := models.User{}
	models.Cookie.Get(c.Ctx, "userinfo", &user)
	beego.Info("xxxxxxxxxxs", user)
	// user.Id = 3
	// user.Phone = "13267745919"
	// user.Password = "e10adc3949ba59abbe56e057f20f883e"
	if len(user.Phone) == 11 { //表示已经登录
		str := fmt.Sprintf(`<ul>
			<li class="userinfo">
				<a href='#'>%v</a>

				<i class="i"></i>
				<ol>
					<li><a href="/user">个人中心</a></li>

					<li><a href="#">我的收藏</a></li>

					<li><a href="/auth/loginOut">退出登录</a></li>
				</ol>

			</li>

		</ul>`, user.Phone)
		c.Data["userinfo"] = str
	} else {
		str := fmt.Sprintf(`<ul>
			<li> <a href="/auth/login" target="_blank">登录</a></li>
			<li>|</li>
			<li><a href="/auth/registerStep1" target="_blank">注册</a></li>
		</ul>`)
		c.Data["userinfo"] = str
	}
	urlPath, _ := url.Parse(c.Ctx.Request.URL.String())
	c.Data["pathname"] = urlPath.Path
}
